package cn.com.dhcc.turbo.service.exch.cmdata;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.dhcc.app.core.CM;
import cn.com.dhcc.app.core.dao.CrudDao;
import cn.com.dhcc.app.core.exception.DaoException;
import cn.com.dhcc.app.core.exception.NiceException;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.service.AbstractCrudService;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.pub.core.consts.AppConst;
import cn.com.dhcc.app.pub.core.consts.AppIocBean;
import cn.com.dhcc.turbo.dao.exch.CarvedDiscsDataDao;
import cn.com.dhcc.turbo.entity.exch.CarvedDiscsData;
import cn.com.dhcc.turbo.entity.exch.CarvedDiscsHistory;
import cn.com.dhcc.turbo.entity.exch.CmData;
import cn.com.dhcc.turbo.entity.exch.CrossNetTmpCmData;
import cn.com.dhcc.turbo.entity.exch.CrossNetTmpFileData;
import cn.com.dhcc.turbo.entity.exch.FileData;
import cn.com.dhcc.turbo.entity.exch.SendCmData;
import cn.com.dhcc.turbo.entity.exch.SendFileData;
import cn.com.dhcc.turbo.service.exch.filedata.CrossNetTmpFileDataService;
import cn.com.dhcc.turbo.service.exch.filedata.FileDataExchageLifecycle;
import cn.com.dhcc.turbo.service.exch.filedata.SendFileDataService;

@Service
public class CarvedDiscsDataService extends AbstractCrudService<CarvedDiscsData> {
	@SuppressWarnings("deprecation")
	private static Logger logger = Log.getExistLogger(LOGTYPE.R);

	@Autowired
	private CarvedDiscsDataDao dao;
	@Autowired
	private CarvedDiscsHistoryService carvedDiscsHistoryService;
	@Autowired
	private SendCmDataService cmDataService;
	@Autowired
	private SendFileDataService sendFileDataService;
	
	@Autowired
	private CrossNetTmpFileDataService crossNetTmpFileDataService;
	@Autowired
	private CrossNetTmpCmDataService crossNetTmpCmDataService;
	@Override
	public CrudDao<CarvedDiscsData> getCrudDao() {
		return dao;
	}

	
	/**
	 * 
	 * @param cmData
	 * @throws ServiceException
	 */
	public void generateCarvedDiscsData(CmData cmData) throws ServiceException {
		try {
			dao.generateCarvedDiscsData(cmData);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}
	
	/**
	 * 计算文件总大小
	 * @param cmData
	 * @throws NiceException
	 */
	public long sumFileSize(WhereCondition condition) throws NiceException {
		try {
			return dao.sumFileSize(condition);
		} catch (DaoException e) {
			logger.error(e);
			throw new NiceException(e);
		}
	}
	

	/**
	 * 根据cmData对象生成对应的CarvedDiscsData对象并且保存起来
	 * @param cmData
	 * @throws DaoException 
	 */
	public void generateCarvedDiscsData(FileData fileData) throws NiceException {
		try {
			dao.generateCarvedDiscsData(fileData);
		} catch (DaoException e) {
			logger.error(e);
			throw new NiceException(e);
		}
	}
	
	/**
	 * 判断数组中的每一个值都等于obj，如果都等于返回true，否则返回false
	 * @param arr
	 * @param obj
	 * @return
	 */
	private  boolean allContains(Object[] arr,Object obj){
		for (int i = 0; i < arr.length; i++) {
			Object object = arr[i];
			if (!obj.equals(object.toString())) {
				return false;
			}
		}
		
		return true;
	}

	/** 
	 * @Description:把list转换为一个用逗号分隔的字符串 
	 */  
	public  String arrayToString(Object[] arr) {  
	    StringBuilder sb = new StringBuilder();  
	    if (arr != null && arr.length > 0) {  
	        for (int i = 0; i < arr.length; i++) {  
	            if (i < arr.length- 1) {  
	                sb.append(arr[i] + ",");  
	            } else {  
	                sb.append(arr[i]);  
	            }  
	        }  
	    }  
	    return sb.toString();  
	}  
	@SuppressWarnings("rawtypes")
	public void generateHistory(CarvedDiscsHistory history,String[] id,String[] filenameIndexs) throws NiceException, ServiceException {
		List<List> dataList=new ArrayList<List>();
		//查询出本次刻盘的list集合
        for (int i = 0; i < id.length; i++) {
			String string = id[i];
			CarvedDiscsData vo = this.get(string);
			if (vo.getPackets()==null || "".equals(vo.getPackets())) {//如果没有拆包
				vo.setStatus("1");//已刻盘
			}else{
				int index=-1;
				for (String indexStr : filenameIndexs[i].split("_")) {
					index=Integer.parseInt(indexStr);
					//更新对应的文件状态为已刻盘
					String[] status=vo.getStatus().split(",");
					status[index]="1";
					vo.setStatus(this.arrayToString(status));
				}
				
			}
			
			if (this.allContains(vo.getStatus().split(","), "1")) {//判断是否该次请求所有的拆包已经下载完成
				if (vo.getDataType().equals(AppConst.ExchDataType.FILE_DATA.value())) {//
	    			WhereCondition parameter = new WhereCondition();
	    			if (vo.getFromTable().equals(AppConst.FromTable.SEND_TABLE.value())) {
	    				parameter.where().eq("group_id", vo.getBatchId()).and().eq("cross_net", AppConst.CrossNetType.INNER_OUT_NETWORK.value());
	        			List<SendFileData> list=sendFileDataService.list(parameter);
	        			dataList.add(list);
					}else if (vo.getFromTable().equals(AppConst.FromTable.TMP_TABLE.value())) {
						parameter.where().eq("group_id", vo.getBatchId()).and().eq("cross_net", AppConst.CrossNetType.OUT_INNER_NETWORK.value())
						.and().eq("THROUGH_GAP", "2");
	        			List<CrossNetTmpFileData> list=crossNetTmpFileDataService.list(parameter);
	        			dataList.add(list);
					}
				}else{
					WhereCondition parameter = new WhereCondition();
	    			if (vo.getFromTable().equals(AppConst.FromTable.SEND_TABLE.value())) {
	        			parameter.where().eq("pid", vo.getBatchId()).and().eq("cross_net", AppConst.CrossNetType.INNER_OUT_NETWORK.value());
	        			List<SendCmData> list=cmDataService.list(parameter);
	        			dataList.add(list);
					}else if (vo.getFromTable().equals(AppConst.FromTable.TMP_TABLE.value())) {
						parameter.where().eq("pid", vo.getBatchId()).and().eq("cross_net", AppConst.CrossNetType.OUT_INNER_NETWORK.value())
						.and().eq("THROUGH_GAP", "2");
	        			List<CrossNetTmpCmData> list=crossNetTmpCmDataService.list(parameter);
	        			dataList.add(list);
					}
				}
			}
			this.update(vo);//更新数据
		}
        
        this.updateStatus(dataList);//更新发送状态
        
        carvedDiscsHistoryService.insert(history);
		
	}

	@SuppressWarnings({ "rawtypes" })
	public void updateStatus(List<List> dataList) throws NiceException {
			CmDataExchangeLifecycle service = (CmDataExchangeLifecycleImpl) CM.getBeanByName(AppIocBean.CM_DATA_EXCHANGE_LIFECYCLE_BEAN);
			FileDataExchageLifecycle service1 = (FileDataExchageLifecycle) CM.getBeanByName(AppIocBean.FILE_DATA_EXCHAGE_LIFECYCLE_BEAN);
			if (dataList!=null && !dataList.isEmpty()) {
				for (List list : dataList) {
					for (Object obj : list) {
						if (obj instanceof SendCmData) {
							CmData cmData=(CmData)obj;
							service.carvedDiscs(cmData);
						}else if (obj instanceof FileData) {
							FileData fileData=(FileData)obj;
							service1.carvedDiscs(fileData);
						}
					}
				}
			}
	}
}
